package com.learn.tomcat.http;

import java.io.IOException;
import java.io.InputStream;

public class Request {

    private InputStream inputStream;
    private String uri;

    public Request(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public void parse() {
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            i = inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++) {
            request.append((char) buffer[j]);
        }
        System.out.println("\n" + request + "\n");
        uri = parseUri(request);
    }

    private String parseUri(StringBuffer request) {
        int index1, index2;
        index1 = request.indexOf(" ");
        if (index1 != -1) {
            index2 = request.indexOf(" ", index1 + 1);
            if (index1 < index2) {
                return request.substring(index1 + 1, index2);
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return "Request{" +
                "inputStream=" + inputStream +
                ", uri='" + uri + '\'' +
                '}';
    }
}
